package cn.bmbanjia.zebra2024.apps.base.clew.service.impl;

import cn.bmbanjia.zebra2024.apps.base.clew.entity.Clew;
import cn.bmbanjia.zebra2024.apps.base.clew.mapper.ClewMapper;
import cn.bmbanjia.zebra2024.apps.base.clew.service.IClewService;
import cn.bmbanjia.zebra2024.apps.base.laddieAppraise.entity.LaddieAppraise;
import cn.bmbanjia.zebra2024.apps.base.laddieAppraise.service.ILaddieAppraiseService;
import cn.bmbanjia.zebra2024.apps.clewAndroid.clew.req.OrderDetailsReq;
import cn.bmbanjia.zebra2024.apps.clewAndroid.clew.resp.OrderDetailsResp;
import cn.bmbanjia.zebra2024.frame.resp.Resp;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import static cn.bmbanjia.zebra2024.apps.base.clew.entity.table.ClewTableDef.CLEW;
import static cn.bmbanjia.zebra2024.apps.base.laddieAppraise.entity.table.LaddieAppraiseTableDef.LADDIE_APPRAISE;

/**
 * 线索 服务层实现。
 *
 * @author fugui
 * @since 2024-07-30
 */
@Slf4j
@Service
public class ClewServiceImpl extends ServiceImpl<ClewMapper, Clew> implements IClewService {

    @Resource
    private ILaddieAppraiseService laddieAppraiseService;

    @Override
    public Resp<OrderDetailsResp> orderDetails(OrderDetailsReq req) {
        Clew clew = getOne(QueryWrapper.create()
                .select(CLEW.ORDER_ID)
                .where(CLEW.ID.eq(req.getClewId())));

        if (ObjUtil.isNotNull(clew) && StrUtil.isNotBlank(clew.getOrderId())) {
            Row row = Db.selectOneBySql("""
                    SELECT
                    	bl.NAME AS leaderName,
                    	bl.phone AS leaderPhone,
                    	bl.id AS leaderId
                    FROM
                    	bm_laddie bl
                    	INNER JOIN bm_order_laddie bol ON bol.laddie_id = bl.id
                    WHERE
                    	bol.team_type = 2
                    	AND bol.`status` IN (3, 4)
                    	and bol.order_id = ?
                    """, clew.getOrderId());
            OrderDetailsResp odr = row.toEntity(OrderDetailsResp.class);
            odr.setOrderId(clew.getOrderId());

            LaddieAppraise la = laddieAppraiseService.getOne(QueryWrapper.create()
                    .select(LADDIE_APPRAISE.SCORE, LADDIE_APPRAISE.APPRAISE_REMARK)
                    .where(LADDIE_APPRAISE.ORDER_ID.eq(clew.getOrderId())));

            if (ObjUtil.isNotNull(la)) {
                odr.setScore(la.getScore());
                odr.setAppraiseRemark(la.getAppraiseRemark());
            }

            return Resp.success(odr);
        }

        return Resp.success();
    }

}
